package trocabi.printer;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;


import org.jopendocument.dom.OOUtils;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;
import trocabi.Socle.JPriceTextField;
import trocabi.model.Article;
import trocabi.model.Depositaire;

public class OpenDocTools {
    private static final Logger logger = Logger.getLogger("trocabi.printer.OpenDocTools");
    private static OpenDocTools instance;
    private SimpleDateFormat    sdf;
    private String              date;

    private OpenDocTools() {
        Calendar cal = Calendar.getInstance();
        sdf = new SimpleDateFormat("dd/MM/yyyy");
        date = sdf.format(cal.getTime());
    }

    public static OpenDocTools getInstance() {
        if (!(instance instanceof OpenDocTools)) {
            instance = new OpenDocTools();
        }
        return instance;
    }

    public String getDescription(Article article) {
        return String.format("%s %s %s %s",
                Article.codeToType(article.getCodeType()),
                Article.codeToAspect(article.getCodeAspect()),
                article.getCouleur(),
                Article.codeToGenre(article.getCodeGenre()));
    }
    
    public void facture_client(List<Article> articles) {
        Sheet   page;
        URL     url = this.getClass().getResource("facture_client.ods"); // TODO:: uniformiser les ressources
        int     ligne = 10; // TODO: magical constante
        double  prix,total=0.0;
        
        if (articles == null || articles.isEmpty()) return;
        try {
            page = SpreadSheet.createFromFile(new File(url.toURI())).getSheet(0);
            page.getCellAt("F7").setValue(date);
            page.setName("Facture client"); // TODO:: libelle
            page.duplicateRows(ligne, 1, articles.size() - 1);
            int  i=0;
            for (Article article: articles) {                    
                page.getCellAt(0, ligne + i).setValue(getDescription(article));
                prix=article.getPrixAchat()+(article.getPrixAchat()*article.getTxMarge());
                page.getCellAt(5, ligne + i).setValue(JPriceTextField.formatPrice(prix)); 
                total += prix;
                i++;
            }
            page.getCellAt(5, ligne + articles.size()).setValue(JPriceTextField.formatPrice(total));
            OOUtils.open(page.getSpreadSheet().saveAs(File.createTempFile("tmp_facture_client", null)));
        } catch (IOException | URISyntaxException e) {
            logger.severe(String.format("%s %s", e.getLocalizedMessage(), e.getMessage()));
        }
    }


    public void printRecuDepositaire(List<Article> articles, Depositaire depositaire) {
        Sheet  page;
        URL    url = this.getClass().getResource("recu_depositaire.ods");
       
        double prix, total=0.0;
        
        if (articles == null || articles.isEmpty()) return;
        try {
            page = SpreadSheet.createFromFile(new File(url.toURI())).getSheet(0);

            int offset = 11;
            page.setName("Reçu dépositaire");
            page.getCellAt("E7").setValue(date);
            page.getCellAt("B5").setValue(depositaire.getNom() + " " + depositaire.getPrenom());
            page.getCellAt("B6").setValue(depositaire.getLibelleRue());
            page.getCellAt("B7").setValue(depositaire.getClass() + " " + depositaire.getLibelleVille());
            page.getCellAt("B8").setValue(depositaire.getTelFixe()+ " " + depositaire.getTelPortable());
            page.getCellAt("B9").setValue(String.valueOf(depositaire.getId()));
            page.duplicateRows(offset, 1, articles.size() - 1);

           
            int i=0;
            for (Article article: articles) {
                page.getCellAt(0, offset + i).setValue(String.valueOf(article.getId()));
                page.getCellAt(1, offset + i).setValue(sdf.format(article.getDateDepot()));
                page.getCellAt(2, offset + i).setValue(article.getDescription());
                page.getCellAt(3, offset + i).setValue(article.getSituation());
                page.getCellAt(4, offset + i).setValue(getDescription(article));

                prix=article.getPrixAchat()+(article.getPrixAchat()*article.getTxMarge());
                page.getCellAt(5, offset + i).setValue(JPriceTextField.formatPrice(prix));
                total += prix;
                i++;
            }
            page.getCellAt(5, offset + articles.size()).setValue(JPriceTextField.formatPrice(total));
            OOUtils.open(page.getSpreadSheet().saveAs(File.createTempFile("tmp_recu_depositaire", null)));
        } catch (IOException | URISyntaxException e) {
            logger.severe(String.format("%s %s", e.getLocalizedMessage(), e.getMessage()));
        }
    }

    public void cahier_ventes(List<Article> articles, Date from, int magasin) {
        URL     url = this.getClass().getResource("cahier_vente.ods");
        Sheet   page;
        int     offset = 11,i=0;
        double  prix, total=0.0;
        
        if (articles == null || articles.isEmpty()) return;
        try {
            page = SpreadSheet.createFromFile(new File(url.toURI())).getSheet(0);     
            String sfrom = sdf.format(from);
            String sto = sdf.format(Calendar.getInstance().getTime());
            page.setName("Cahier de vente");
            page.getCellAt("D6").setValue(sfrom);
            page.getCellAt("D7").setValue(sto);
            page.getCellAt("B6").setValue(String.valueOf(magasin));
            page.duplicateRows(offset, 1, articles.size() - 1);

            for (Article article: articles) {
                page.getCellAt(0, offset + i).setValue(sdf.format(article.getDateChangementEtat()));
                page.getCellAt(1, offset + i).setValue(String.valueOf(article.getIdDepositaire()));
                page.getCellAt(2, offset + i).setValue(String.valueOf(article.getId()));

                page.getCellAt(3, offset + i).setValue(getDescription(article));
                prix=article.getPrixAchat()+(article.getPrixAchat()*article.getTxMarge());
                page.getCellAt(4, offset + i).setValue(JPriceTextField.formatPrice(prix));
                total += prix;
                i++;
            }
            page.getCellAt(4, offset + articles.size()).setValue(JPriceTextField.formatPrice(total));
            OOUtils.open(page.getSpreadSheet().saveAs(File.createTempFile("tmp_cahier_vente", null)));
        } catch (IOException | URISyntaxException e) {
            logger.severe(String.format("%s %s", e.getLocalizedMessage(), e.getMessage()));
        }
    }

    public void facture_depositaire(List<Article> articles, Depositaire depositaire) {
        Sheet page;
        URL url = this.getClass().getResource("facture_depositaire.ods");
        if (articles == null || articles.isEmpty()) return;
        try {
            page = SpreadSheet.createFromFile(new File(url.toURI())).getSheet(0);

            int offset = 11;
            page.getCellAt("E7").setValue(date);
            page.getCellAt("B5").setValue(depositaire.getNom() + " " + depositaire.getPrenom());
            page.getCellAt("B6").setValue(depositaire.getLibelleRue());
            page.getCellAt("B7").setValue(depositaire.getCodePostal() + " " + depositaire.getLibelleVille());
            page.getCellAt("B8").setValue(depositaire.getTelFixe() + " " + depositaire.getTelPortable());
            page.getCellAt("B9").setValue(String.valueOf(depositaire.getId()));
            page.setName("Facture dépositaire");
            if (articles.size() != 1) {
                page.duplicateRows(offset, 1, articles.size() - 1);
            }

            double total = 0.0;
            double prixPaye = 0;
            int i = 0;
            for (Article article : articles) {
                page.getCellAt(0, offset + i).setValue(String.valueOf(article.getId()));
                page.getCellAt(1, offset + i).setValue(sdf.format(article.getDateDepot()));
                page.getCellAt(2, offset + i).setValue(getDescription(article));
                page.getCellAt(3, offset + i).setValue(article.getSituation());

                double prixAchat = article.getPrixAchat();
                page.getCellAt(4, offset + i).setValue(JPriceTextField.formatPrice(article.getPrixAchat()));
                if (article.getDatePaiementDepositaire()!=null) {
                    page.getCellAt(5, offset + i).setValue("Payé le " + sdf.format(article.getDatePaiementDepositaire()));
                    prixPaye += prixAchat;
                } 
                else {
                    page.getCellAt(5, offset + i).setValue("En attente");
                }
                total += prixAchat;
                i++;
            }
            page.getCellAt(4, offset + articles.size() + 1).setValue(JPriceTextField.formatPrice(total));
            page.getCellAt(5, offset + articles.size() + 1).setValue(JPriceTextField.formatPrice(prixPaye));
            OOUtils.open(page.getSpreadSheet().saveAs(File.createTempFile("tmp_facture_depositaire", null)));
        } catch (IOException | URISyntaxException e) {
            logger.severe(String.format("%s %s", e.getLocalizedMessage(), e.getMessage()));
        }
    }
}
